<script setup>
import { postAddCollection, postCancelCollection } from '@/axios/api/posts'
import PostMaster from '@/components/PostMaster.vue'
import UserAvatar from '@/components/UserAvatar/UserAvatar.vue'
import LfDropdownPanel from '@/components/commonUI/LfDropdownPanel.vue'
import CommentLineIcon from '@/components/svgComponents/CommentLineIcon.vue'
import LikeIcon from '@/components/svgComponents/LikeIcon.vue'
import LikeLineIcon from '@/components/svgComponents/LikeLineIcon.vue'
import ShareIcon from '@/components/svgComponents/ShareIcon.vue'
import { useOptimisticUpdate } from '@/composables/useOptimisticUpdate'
import { decryptUrl } from '@/utils/dataUtils'
import { getDateTimeStr } from '@/utils/transIUtils'
import TopicExploreListItem from '@/views/TopicExplore/TopicExploreListItem.vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import PostDetailPicture from './PostDetailPicture.vue'
import LfButton from '@/components/commonUI/LfButton.vue'
// import LfMenu from '@/components/commonUI/LfMenu.vue'
import { MoreFilled } from '@element-plus/icons-vue'
import { computed, ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import ReportDialog from '@/components/commonUI/ReportDialog.vue'
import { Pointer, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Vote from './Vote.vue'
import { get } from '@/axios/utils/request'
import { useGlobalStore } from '@/stores/globalStore'

const globalStore = useGlobalStore()



const router = useRouter()
const route = useRoute()

const props = defineProps({
  data: Object,
  isGallery: {
    type: Boolean,
    default: false,
  },
})


const postId = ref(route.params.id)

const { updatePostDetail } = useOptimisticUpdate()

const addCollection = () => {
  // 乐观更新数据
  updatePostDetail(postId, (oldData) => ({
    ...oldData,
    isCollection: true,
    collectionCount: oldData.collectionCount + 1,
  }))

  // 发送API请求
  postAddCollection({ id: props.data.id, uid: props.data.uid }).catch(() => {
    // 如果请求失败，回滚更新
    updatePostDetail(postId, (oldData) => ({
      ...oldData,
      isCollection: false,
      collectionCount: oldData.collectionCount - 1,
    }))
  })
}

const cancelCollection = () => {
  // 乐观更新数据
  updatePostDetail(postId, (oldData) => ({
    ...oldData,
    isCollection: false,
    collectionCount: oldData.collectionCount - 1,
  }))

  // 发送API请求
  postCancelCollection({ id: props.data.id, uid: props.data.uid }).catch(() => {
    // 如果请求失败，回滚更新
    updatePostDetail(postId, (oldData) => ({
      ...oldData,
      isCollection: true,
      collectionCount: oldData.collectionCount + 1,
    }))
  })
}

const handleDiscussClick = () => {
  router.push(`/topic/${props.data.topicId}/discuss/${props.data.discussId}`)
}

const handelShare = () => {
  const text = window.location.href
  if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
    navigator.clipboard.writeText(text)
      .then(() => {
        ElMessage.success('链接已复制到剪贴板')
      })
      .catch(() => {
        fallbackCopyTextToClipboard(text)
      })
  } else {
    fallbackCopyTextToClipboard(text)
  }
}

function fallbackCopyTextToClipboard(text) {
  // 创建临时 input
  const input = document.createElement('input')
  input.value = text
  document.body.appendChild(input)
  input.select()
  try {
    document.execCommand('copy')
    ElMessage.success('链接已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败，请手动复制链接')
  }
  document.body.removeChild(input)
}

// 举报相关
const showReportDialog = ref(false)
const reportInfo = ref({
  type: 'post',
  id: props.data?.id,
  title: props.data?.title,
  content: props.data?.content,
})

// 处理举报成功
const handleReportSuccess = () => {
  ElMessage.success('举报已提交，我们会尽快处理')
}

const emit = defineEmits(['refresh'])

// const followLoading = ref(false)
const handleFollow = async () => {
  // if (followLoading.value) return
  // followLoading.value = true
  try {
    await get('/post/fabulous/thumb', { id: postId.value })
    ElMessage.success('关注成功')
    emit('refresh')
    globalStore.setRefreshollowPost(!globalStore.refreshollowPost)
    // window.location.reload()

  } finally {
    // followLoading.value = false
  }
}
const handleUnfollow = async () => {
  // if (followLoading.value) return
  // followLoading.value = true
  try {
    await get('/post/fabulous/cancel', { id: postId.value })
    ElMessage.success('已取消关注')
    emit('refresh')
    globalStore.setRefreshollowPost(!globalStore.refreshollowPost)

    // window.location.reload()

  } finally {
    // followLoading.value = false
  }
}
</script>

<template>
  <div class="post-detail-main p-4 pt-2 flex flex-col">
    <section class="split-line-b pb-2 flex flex-col items-start">
      <!-- <LfDropdownPanel position="right">
        <img :src="data.topicInfo?.coverImage" alt="" class="w-12 h-12 object-cover rounded-full cursor-pointer" />

        <template #content>
          <div class="w-[250px] bg-[--fill-0] rounded-lg shadow-lg">
            <TopicExploreListItem :item="data.topicInfo" />
          </div>
        </template>
</LfDropdownPanel> -->
      <div class="text-2xl font-medium select-text text-blue-700">{{ data?.title }}</div>
      <div v-if="data?.discussName" @click="handleDiscussClick" class="text-blue-500 cursor-pointer w-fit">
        #{{ data?.discussName }}
      </div>
    </section>

    <section class="flex gap-4 py-5">
      <UserAvatar :avatar="data?.userInfo?.avatar" :userId="data?.userInfo?.uid" />
      <div class="flex-1">
        <div class="flex items-center">
          <span class="font-medium text-sm mr-1">{{ data?.userInfo?.username }}</span>
          <PostMaster class="mr-2" />
          <span class="text-xs">{{ getDateTimeStr(dayjs(data?.createTime).valueOf()) }}</span>
        </div>
        <div>
          <div v-if="data?.type === 1 || data?.type === 3" class="editor-content-view">
            <div v-html="data?.content"></div>
          </div>
          <div v-else class="select-text">{{ data?.content }}</div>

          <!-- 视频 -->
          <div v-if="data?.type === 2 && !isGallery" class="w-[350px]">
            <video :src="JSON.parse(decryptUrl(data?.media[0]))[0]" class="w-full h-full object-cover rounded-lg"
              controls />
          </div>

          <!-- 图片 -->
          <PostDetailPicture v-if="data?.type !== 3 && data?.type !== 2 && !isGallery" :media="data?.media" />

          <!-- 投票 -->
          <Vote v-if="data?.type === 4" :data="data?.voteInfo" :isVoteResult="data?.isVoteResult"
            :myVoteResult="data?.myVoteResult" />
        </div>
      </div>

    </section>

    <section class="post-actions-bar flex items-center gap-4 flex-wrap relative pb-14">
      <div class="flex items-center gap-4 flex-wrap flex-1 min-w-0">
        <LfButton type="secondary" size="small" needLogin>
          <div class="flex items-center gap-1">
            <el-icon>
              <View />
            </el-icon>
            <div class="text-sm">{{ data?.readCount>9999 ? '9999+' : data?.readCount }}</div>
          </div>
        </LfButton>
        <LfButton @click="data.isCollection ? cancelCollection() : addCollection()" type="secondary" size="small"
          needLogin>
          <div class="flex items-center gap-1">
            <LikeIcon v-if="data?.isCollection" class="w-4 like-animation" color="red" />
            <LikeLineIcon v-else class="w-4" />
            <div class="text-sm">{{ data?.collectionCount>9999 ? '9999+' : data?.collectionCount }}</div>
          </div>
        </LfButton>
        
        <LfButton type="secondary" size="small" needLogin>
          <div class="flex items-center gap-1">
            <CommentLineIcon class="w-4" />
            <div class="text-sm">{{ data?.commentCount>9999 ? '9999+' : data?.commentCount }}</div>
          </div>
        </LfButton>
        
        <LfButton type="secondary" size="small" @click="handelShare">
          <div class="flex items-center gap-1">
            <ShareIcon class="w-4" color="#000000" />
            <div class="text-sm">分享</div>
          </div>
        </LfButton>
        <LfButton type="secondary" size="small" @click="showReportDialog = true">
          <div class="flex items-center gap-1">
            <el-icon>
              <Pointer />
            </el-icon>
            <div class="text-sm">举报</div>
          </div>
        </LfButton>
      </div>
      <div class="flex-shrink-0 ml-auto">
        <LfButton v-if="!data?.isFabulous" @click="handleFollow" :loading="followLoading" type="primary" size="small"
          needLogin>
          关注
        </LfButton>
        <LfButton v-else type="secondary" @click="handleUnfollow" :loading="followLoading" size="small" needLogin>
          取消关注
        </LfButton>
      </div>
      <ReportDialog v-model="showReportDialog" :report-info="reportInfo" :type="1" @success="handleReportSuccess" />
    </section>
  </div>
</template>

<style scoped lang="scss">
.like-animation {
  animation: likeScale 0.3s ease;
}

.post-detail-main {
  min-width: 636px;
  max-width: 1280px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

@media (max-width: 900px) {
  .post-detail-main {
    min-width: 636px;
    max-width: 100vw;
    padding-left: 0;
    padding-right: 0;
  }
}

@media (max-width: 700px) {
  .post-detail-main {
    min-width: 100vw;
    max-width: 100vw;
    padding-left: 0;
    padding-right: 0;
  }
}

@media (min-width: 1680px) {
  .post-detail-main {
    min-width: 800px;
    max-width: 100vw;
    padding-left: 0;
    padding-right: 0;
  }
}

@media (min-width: 1920px) {
  .post-detail-main {
    min-width: 1000px;
    max-width: 100vw;
    padding-left: 0;
    padding-right: 0;
  }
}

.post-actions-bar {
  border-top: 1px solid #f0f2f5;
  padding-top: 8px;
  margin-top: 8px;
  background: transparent;
  min-height: 48px;
}

.follow-btn-zhihu {
  background: #1765ad;
  color: #fff;
  border-radius: 20px;
  font-weight: 600;
  padding: 0 22px;
  height: 36px;
  font-size: 15px;
  box-shadow: 0 2px 8px 0 rgba(56, 112, 255, 0.08);
  border: none;
  transition: background 0.2s;
}

.follow-btn-zhihu:hover {
  background: #145399;
}

.unfollow-btn-zhihu {
  background: #f3f4f6;
  color: #1765ad;
  border-radius: 20px;
  font-weight: 600;
  padding: 0 22px;
  height: 36px;
  font-size: 15px;
  border: 1px solid #bcd7f7;
  transition: background 0.2s, color 0.2s;
}

.unfollow-btn-zhihu:hover {
  background: #e6f0fa;
  color: #145399;
}

@keyframes likeScale {
  0% {
    transform: scale(0.5);
  }

  50% {
    transform: scale(1.3);
  }

  100% {
    transform: scale(1);
  }
}
</style>
<style>
.editor-content-view {
  border-radius: 5px;
  padding: 0 10px;
  margin-top: 20px;
  overflow-x: auto;
}

.editor-content-view p,
.editor-content-view li {
  white-space: pre-wrap;
  /* 保留空格 */
}

.editor-content-view blockquote {
  border-left: 8px solid #d0e5f2;
  padding: 10px 10px;
  margin: 10px 0;
  background-color: #f1f1f1;
}

.editor-content-view code {
  font-family: monospace;
  background-color: #eee;
  padding: 3px;
  border-radius: 3px;
}

.editor-content-view pre>code {
  display: block;
  padding: 10px;
}

.editor-content-view table {
  border-collapse: collapse;
}

.editor-content-view td,
.editor-content-view th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

.editor-content-view th {
  background-color: #f1f1f1;
}

.editor-content-view ul,
.editor-content-view ol {
  padding-left: 20px;
}

.editor-content-view input[type="checkbox"] {
  margin-right: 5px;
}

.editor-content-view hr {
  border-radius: 3px;
  margin: 20px auto;
}
</style>